<template>
  <div class="login">
    <div class="bg">
      <img src="../assets/login/bg.png" />
    </div>
    <div class="bg_logo">
      <img v-if="makeng == true" src="../assets/login/bg_logo.png" />
      <img v-if="qiucheng == true" src="../assets/login/qc.png" />
    </div>
    <img src="../assets/login/bg_form_border.png" width="400" />
    <div class="login_box">
      <!-- 登录表单区域 -->
      <el-form
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        size="mini"
        v-loading="isSubmitting"
        element-loading-background="rgba(0, 0, 0, 0.2)"
        @keyup.enter.native="handleLogin"
      >
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            placeholder="请输入密码"
            show-password
            prefix-icon="el-icon-lock"
          ></el-input>
        </el-form-item>
        <!-- 验证码 -->
        <el-form-item prop="code codeBox">
          <el-input
            v-model="loginForm.code"
            class="code"
            placeholder="验证码"
            prefix-icon="el-icon-circle-check"
          ></el-input>
          <a @click="getVerifyCode" class="codeImg code">
            <img :src="imgSrc" alt="" />
          </a>
        </el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button @click="handleLogin">安全登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { INDEX } from "~/router";
import axios from "axios";
import md5 from "js-md5";
import { BACKEND_ROOT } from "../Contants";
import {MUTATION_UPDATE_USER_INFO} from "../vuex/auth";
import store from "../vuex/store";


export default {
  data() {
    return {
      loginForm: {
        username: "",
        password: "",
        code: null,
      },
      makeng: false,
      imgSrc: "",
      qiucheng: false,
      loginRules: {
        username: [
          {
            required: true,
            trigger: "blur",
            message: "用户名不能为空",
          },
        ],
        password: [
          {
            required: true,
            trigger: "blur",
            message: "密码错误，请重试",
          },
        ],
        code: [
          { required: true, trigger: "change", message: "验证码不能为空" },
        ],
      },
      isSubmitting: false,
    };
  },
  beforeRouteEnter(from,to,next){
    if(store.state.auth.hasLogin){
        const forward = to.query.to || INDEX;
        next(forward);
    }else{
        next();
    }
  },
  methods: {
    async handleLogin() {
      if(this.isSubmitting){
        return undefined;
      }
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          const data = {
            password: md5(this.loginForm.password),
            platformCode: this.$route.params.enterprise,
            userName: this.loginForm.username,
            validateCode: this.loginForm.code,
          };
          const formData = new FormData();
          for (const [key, value] of Object.entries(data)) {
            formData.append(key, value);
          }
          const enterprise = this.$route.params.enterprise;
          const url = `/unitPlatform/getUnitPlatformByCode/${enterprise}`;
          this.isSubmitting = true;
          axios({
            url,
            method: "get",
          }).then((res) => {
            console.log(res);
            if (res.data.resultCode == "200") {
              // 存储untid信息
              window.sessionStorage.setItem(
                "unitId",
                res.data.parameter.unitId
              );
              window.sessionStorage.setItem("logo", res.data.parameter.logo);
              window.sessionStorage.setItem(
                "platformName",
                res.data.parameter.platformName
              );
              window.sessionStorage.setItem("id", res.data.parameter.id);
              console.log("用户登录",formData);
              axios({
                url: "/web/login",
                method: "post",
                data: formData,
              }).then((res) => {
                if (res.data.resultCode === "200") {
                  window.sessionStorage.setItem(
                    "userId",
                    res.data.parameter.userId
                  );
                  const userInfo = res.data.parameter;
                  this.$store.commit(MUTATION_UPDATE_USER_INFO, { userInfo, loginSuccess: true })
                }
                if (res.data.resultCode === "204") {
                  this.$message.error("用户不存在");
                } else if (res.data.resultCode === "200") {
                  // 登陆成功，跳转到首页
                  const to = this.$route.query.to || INDEX;
                  this.$router.replace(to);
                  return undefined;
                } else if (res.data.resultCode === "206") {
                  this.$message.error("用户密码错误");
                } else if (res.data.resultCode === "422") {
                  this.$message.error("用户名为空");
                } else if (res.data.resultCode === "424") {
                  this.$message.error("用户无权限");
                } else if (res.data.resultCode === "418") {
                  this.$message.error("验证码错误");
                }
                this.getVerifyCode();
              }).finally(()=>{
                this.isSubmitting = false;
              });
            } else {
              console.log(res);
            }
          });
        }
      });
    },
    getVerifyCode() {
      axios({
        // url: "http://221.231.138.86:41085/enterprise/web/verifyCode",
        url: BACKEND_ROOT +"/web/verifyCode",
        method: "get",
        responseType: "blob",
      }).then((res) => {
        const url = window.URL.createObjectURL(res.data);
        console.log("构造验证码",url);
        this.imgSrc = url;
      });
    },
  },
  components: {},
  created() {
    var that = this;
    if (this.$route.params.enterprise == "makeng") {
      document.title = "福建马坑矿业股份有限公司陈坑尾矿库";
      this.makeng = true;
    }
    if (this.$route.params.enterprise == "qiucheng") {
      document.title = "德化县丘埕矿业有限公司";
      this.qiucheng = true;
    }
  },
  mounted() {
    this.getVerifyCode();
  },
};
</script>

<style scoped>
.bg {
  position: fixed;
  right: 0;
  bottom: 0;
  min-width: 100%;
  min-height: 100%;
  height: auto;
  width: auto;
  z-index: -10;
  animation: pulse 10s infinite;
}
@keyframes pulse {
  0% {
    transform: scale(1, 1);
  }
  50% {
    transform: scale(1.25, 1.25);
  }
  100% {
    transform: scale(1, 1);
  }
}
.login > img {
  position: absolute;
  left: 60%;
  top: 50%;
  transform: translate(43.5%, -55%);
}
.bg_logo {
  font-size: 30px;

  width: 290px;
  position: absolute;
  left: 60%;
  top: 50%;
  transform: translate(80%, -320%);
}
.bg_logo img {
  height: 100%;
  width: 100%;
}
.login_box {
  width: 290px;
  height: 300px;
  border-radius: 5px;
  position: absolute;
  left: 60%;
  top: 50%;
  transform: translate(80%, -60%);
}
.el-form {
  padding: 32px;
  position: absolute;
  bottom: 0;
  width: 100%;
  box-sizing: border-box;
}
.el-input >>> .el-input__inner {
  background-color: #2f2f31af;
  border: 1px solid rgba(207, 203, 203, 0.836);
  color: white;
  border-radius: 10px;
}
.el-button {
  width: 100%;
  border-radius: 10px;
  color: black;
}
.code {
  width: 50%;
}

.codeImg {
  position: relative;
  top: 10px;
  left: 20px;
}
</style>
